package v1alpha3

import (
	"github.com/emicklei/go-restful"
	"k8s.io/klog"
	"kubeconsole/api"
	"kubeconsole/apiserver/query"
	"kubeconsole/client/informers"
	"kubeconsole/models/resources/v1alpha3/resource"
)

type Handler struct {
	resourceGetterV1alpha3 *resource.ResourceGetter
}

func New(factory informers.InformerFactory) *Handler {
	return &Handler{
		resourceGetterV1alpha3: resource.NewResourceGetter(factory),
	}
}

func (h *Handler) handleGetResources(request *restful.Request, response *restful.Response) {
	namespace := request.PathParameter("namespace")
	resourceType := request.PathParameter("resources")
	name := request.PathParameter("name")

	result, err := h.resourceGetterV1alpha3.Get(resourceType, namespace, name)
	if err == nil {
		response.WriteEntity(result)
		return
	}

	if err != resource.ErrResourceNotSupported {
		klog.Error(err)
		api.HandleInternalError(response, nil, err)
		return
	}

}

// handleListResources retrieves resources
func (h *Handler) handleListResources(request *restful.Request, response *restful.Response) {
	query := query.ParseQueryParameter(request)
	resourceType := request.PathParameter("resources")
	namespace := request.PathParameter("namespace")

	result, err := h.resourceGetterV1alpha3.List(resourceType, namespace, query)

	if err == nil {
		response.WriteEntity(result)
		return
	}

	if err != resource.ErrResourceNotSupported {
		klog.Error(err)
		api.HandleInternalError(response, nil, err)
		return
	}

}
